<template>
  <div>
    <div class="head_">
      <el-button type="primary" size="small" @click="add">添加</el-button>
    </div>
    <div class="table">
      <el-table :data="tableData">
        <el-table-column label="ID" width="50px" align="center">
          <template slot-scope="scope">
            <span>{{scope.row.id}}</span>
          </template>
        </el-table-column>
        <el-table-column label="图片" align="center">
          <template slot-scope="scope">
            <img style="width:50px;height:50px" :src="scope.row.image" />
          </template>
        </el-table-column>
        <el-table-column label="链接" align="center">
          <template slot-scope="scope">
            <span>{{scope.row.url}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center">
          <template slot="header" slot-scope="scope">
            <el-select v-model="position" placeholder="位置"  @change="initData" clearable >
              <el-option
                v-for="item in checkboxs"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </template>
          <template slot-scope="scope">
            <span>{{scope.row.positionName}}</span>
          </template>
        </el-table-column>
        <el-table-column label="排序" align="center">
          <template slot-scope="scope">
            <span>{{scope.row.orderBy}}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.showStatus"
              :active-value="activeValue"
              :inactive-value="inactiveValue"
              @change="changeStatus(scope.row.id)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center">
          <template slot-scope="scope">
            <span>{{scope.row.createTime}}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="150px">
          <template slot-scope="scope">
            <el-button size="mini" @click="edit(scope.row)">编辑</el-button>
            <el-button type="danger" size="mini" @click="del(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="page">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
          :current-page="index"
          :page-size="pageSize"
          :page-sizes="[10,20]"
          layout="total,sizes,prev, pager, next,jumper"
          :total="total"
        ></el-pagination>
      </div>
    </div>
    <el-dialog :title="title" :visible.sync="visible" width="500px">
      <el-form :model="form" label-width="80px" :rules="rules" ref="form">
        <el-form-item label="广告名称" prop="name">
          <el-input placeholder="输入广告名称" v-model="form.name" style="width:350px" />
        </el-form-item>
        <el-form-item label="广告位置" prop="position">
          <el-select v-model="form.position" placeholder="请选择">
            <el-option v-for="item in checkboxs" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="广告图片" prop="image">
          <el-upload
            :action="action"
            :headers="header"
            list-type="picture"
            :limit="limit"
            :on-exceed="exceed"
            :file-list="fileList"
            :on-success="uploadSuccess"
            :on-remove="remove"
          >
            <el-button v-if="fileList.length==0" type="primary" size="small">上传图片</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="广告链接" prop="url">
          <el-input placeholder="输入广告链接" v-model="form.url" style="width:350px" />
        </el-form-item>
        <el-form-item label="广告排序" prop="orderBy">
          <el-input placeholder="值越大越靠后" v-model.number="form.orderBy" style="width:350px" />
        </el-form-item>
        <el-form-item label="广告状态" prop="showStatus">
          <el-switch
            v-model="form.showStatus"
            :active-value="activeValue"
            :inactive-value="inactiveValue"
          ></el-switch>
        </el-form-item>
      </el-form>
      <div class="bot">
        <el-button type="primary" size="small" @click="save()">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { add, del, changeStatus, list } from "../../../api/ad.js";
import { getToken } from "@/utils/auth.js";
export default {
  data() {
    return {
      activeValue: 0,
      inactiveValue: 1,
      editId: null,
      action: "",
      limit: 1,
      header: {},
      fileList: [],
      form: {
        id: null,
        image: "",
        name: "",
        showStatus: 1,
        url: "",
        orderBy: 0,
        position: ""
      },
      visible: false,
      title: "添加",
      index: 1,
      pageSize: 10,
      position: null,
      tableData: [],
      total: 0,
      rules: {
        name: [{ required: true, message: "请输入名称", trigger: "blur" }],
        position: [{ required: true, message: "请选择", trigger: "change" }],
        image: [
          { required: true, message: "请上传图片" },
          { type: "url", message: "格式错误" }
        ],
        url: [{ required: true, message: "请输入链接", trigger: "blur" }],
        orderBy: [
          {
            type: "number",
            required: true,
            message: "请输入正确的排序",
            trigger: "blur"
          }
        ]
      },
      checkboxs: [
        { id: 1, name: "首页主要广告" },
        { id: 2, name: "首页限时广告" },
        { id: 3, name: "首页团购广告" }
      ]
    };
  },
  mounted() {
    this.initData();
    this.action = this.$UPLOAD;
    this.header = { token: getToken() };
  },
  methods: {
    changeStatus(id) {
      changeStatus(id).then(res => {
        this.initData();
      });
    },
    del(id) {
      this.$confirm("确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          del(id).then(res => {
            this.$message({
              type: "success",
              message: "删除成功!"
            });
            this.initData();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    handleSizeChange(size) {
      this.pageSize = size;
      this.initData();
    },
    handleCurrentChange(page) {
      this.index = page;
      this.initData();
    },
    //根据链接获取图片名称
    getNameByUrl(url) {
      let index = url.lastIndexOf("/");
      return url.substring(index + 1);
    },
    edit(data) {
      this.title = "编辑";
      this.visible = true;
      this.form = data;
      this.fileList = [];
      this.fileList.push({
        name: this.getNameByUrl(data.image),
        url: data.image
      });
    },
    /**
     * 重置表单
     */
    restForm() {
      this.form = {
        id: null,
        image: "",
        name: "",
        showStatus: 1,
        url: "",
        orderBy: 0,
        position: ""
      };
    },
    /**
     * 保存
     */
    save() {
      if (this.fileList.length != 0) {
        if (this.fileList[0].response != null) {
          this.form.image = this.fileList[0].response.data;
        } else {
          this.form.image = this.fileList[0].url;
        }
      }
      console.log(this.form.image);
      this.$refs["form"].validate(s => {
        if (s) {
          add(this.form).then(res => {
            this.restForm();
            this.initData();
            this.visible = false;
            this.$message({
              type: "success",
              message: res.message
            });
          });
        }
      });
    },
    /**
     * 移除成功
     */
    remove(file, fileList) {
      this.fileList = fileList;
    },
    /**
     * 上传成功
     */
    uploadSuccess(response, file, fileList) {
      if (response.code === 2000) {
        this.fileList = fileList;
      } else {
        this.$message({
          type: "warning",
          message: response.message
        });
      }
    },

    /**
     * 超出图片限制
     */
    exceed() {
      this.$message({
        type: "warning",
        message: "超出限制"
      });
    },
    add() {
      this.title = "添加";
      this.visible = true;
      this.fileList = [];
      this.restForm();
    },
    initData() {
      list(this.position, this.index, this.pageSize).then(res => {
        this.tableData = res.data.records;
        this.total = res.data.total;
      });
    }
   
  }
};
</script>

<style scoped>
.head_ {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;
}
.table {
  background-color: #ffffff;
}
.table_op {
  display: flex;
  flex-wrap: wrap;
  padding: 20px 20px 0 20px;
  box-sizing: border-box;
  width: 100%;
}
.bot {
  width: 100%;
  display: flex;
  justify-content: flex-end;
}
.page {
  width: 100%;
  display: flex;
  justify-content: center;
  height: 100px;
  align-items: center;
}
</style>
